/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.web.approvalformat.rpc.config;

import com.inspur.edp.web.approvalformat.rpc.webservice.impl.RtcValidationApproveWebServiceImpl;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import io.iec.edp.caf.rest.RESTEndpoint;
import io.iec.edp.caf.rest.RESTServiceRegistrar;
import io.iec.edp.caf.sumgr.api.IServiceUnitAware;
import io.iec.edp.caf.sumgr.api.entity.ServiceUnitInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.util.List;
import java.util.Optional;

@Configuration(proxyBeanMethods = false)
@EnableTransactionManagement
public class RtcValidationApproveConfiguration {

    private final IServiceUnitAware suService = SpringBeanUtils.getBean(IServiceUnitAware.class);
    private final Logger logger = LoggerFactory.getLogger(RtcValidationApproveConfiguration.class);

    public RtcValidationApproveConfiguration() {
        RESTServiceRegistrar restServiceRegistrar = RESTServiceRegistrar.getSingleton();
        List<String> serverUnits = suService.getEnabledServiceUnits();
        List<ServiceUnitInfo> allServiceUnitList = suService.getAllServiceUnits();
        for (String su : serverUnits) {
            Optional<ServiceUnitInfo> findServiceUnitInfo = allServiceUnitList.stream().filter(t -> t.getName().equalsIgnoreCase(su)).findFirst();
            if (findServiceUnitInfo.isPresent()) {
                if (!StringUtils.isEmpty( findServiceUnitInfo.get().getApplicationName())) {
                    String ep = "/" + findServiceUnitInfo.get().getApplicationName().toLowerCase() + "/" + su.toLowerCase() + "/v1.0/mobileapprove/check";
                    logger.info("MAF register before navigate approve web api: " + ep);
                    restServiceRegistrar.registerRestEndpoint(new RESTEndpoint(ep, new RtcValidationApproveWebServiceImpl()));
                } else {
                    logger.info("MAF:关键应用为空，对应SU为：" + su.toLowerCase());
                }
            }
        }
    }

}
